/*
 * TMap Designer - A Thematic Map design software
 * Copyright (C) 2006 World Health Organization
 * http://www.who.int
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package who.tmap.util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

import javax.swing.ImageIcon;

import org.apache.log4j.Logger;
import org.jdom.Element;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import who.tmap.common.Constants;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;

/**
 * @author stl
 *
 */
public class MiscHelper {
    
    private static Logger logger = Logger.getLogger(MiscHelper.class);
    
	private static final String WEB_START_PROPERTY ="jnlpx.heapsize";
    
    private static String osName =System.getProperty( "os.name" ).toUpperCase();
    private static boolean macOS =osName.indexOf("MAC") != -1; 
    
    private static boolean webStart =System.getProperty( WEB_START_PROPERTY ) != null;
    
    public BufferedImage convertToBufferedImage( Image img ) {
    	BufferedImage bufferedImage =new BufferedImage( img.getWidth(null), 
    													img.getHeight(null), 
    													BufferedImage.TYPE_INT_RGB );
    	
    	Graphics2D bufImageGraphics = bufferedImage.createGraphics();
    	boolean done =bufImageGraphics.drawImage(img, 0, 0, null);
    	logger.info( "convertToBufferedImage=" + done );
	   
    	return bufferedImage;
    }
    
    public ImageIcon getImageIcon( String imgName ) {
        return new ImageIcon( getClass().getResource(Constants.IMAGE_PATH + imgName) );
    }
    
    public BufferedImage getJPEGBufferedImage( String jpegFileName ) throws ImageFormatException, IOException {
    	InputStream in =getClass().getResourceAsStream( Constants.IMAGE_PATH + jpegFileName );
    	
    	JPEGImageDecoder decoder =JPEGCodec.createJPEGDecoder( in );
    	BufferedImage image =decoder.decodeAsBufferedImage(); 	
    	
    	in.close();

    	return image;
    }  
    
	public String colorToHexa( Color color ) {
		return getHexa( color.getRed() ) + getHexa( color.getGreen() ) + getHexa( color.getBlue() ) ;
	}
	
	public String getHexa( int b ) {
		return Integer.toString( ( b & 0xff ) + 0x100, 16 ).substring( 1 );
	}	
	
	public Color rgbToColor( String rgb ) {		
		return new Color( Integer.parseInt( rgb.trim(), 16 ) ); 
	}	 
	
	public byte[] loadInlineImage( Element elt ) throws Exception {
		String b64Img =elt.getTextNormalize();
		
		// Remove space character added when saving the base64 string
        int s = 0;
        int e = 0;
        StringBuffer result = new StringBuffer();
        
        while ((e = b64Img.indexOf(32, s)) >= 0) {
            result.append(b64Img.substring(s, e));
            s = e+1;
        }
        result.append(b64Img.substring(s));	    		
		
		byte[] imageData = new BASE64Decoder().decodeBuffer(result.toString());
		
		return imageData;
	}
	
	public String saveInlineImage( byte[] imageBytes ) {
		return new BASE64Encoder().encode( imageBytes );
	}	
    
	/**
	 * Returns the operating system name
	 * @return
	 */
    public static String getOSName() {
        return osName;
    }
    
    /**
     * Is TMap Designer running on Mac OS ?
     * @return
     */
    public static boolean isMacOS() {
        return macOS;
    }
    
    public static boolean isWebStart() {
    	return webStart;
    } 

}
